//
//  AppDelegate.swift
//  miaoyin
//
//  Created by David on 2017/2/14.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate, WXApiDelegate {

    var window: UIWindow?
    var tabController: FCTabViewController!
    
    var firstVC: FirstViewController!
    var wodeVC: WodeViewController!
    
    var payView: PayView?
    
    var wodeVCLoaded = false
    
//    var tencentApi: TencentApi!
    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        
        tabController = FCTabViewController()
        firstVC = FirstViewController()
        let nav1 = UINavigationController(rootViewController: firstVC)
        let btnPH = UIViewController()
        wodeVC = WodeViewController()
        let nav2 = UINavigationController(rootViewController: wodeVC)
        
        nav1.navigationBar.barStyle = .blackTranslucent
        nav1.navigationBar.tintColor = UIColor.white
        nav1.navigationBar.barTintColor = themeColor2
        
        nav2.navigationBar.barStyle = .blackTranslucent
        nav2.navigationBar.tintColor = UIColor.white
        nav2.navigationBar.barTintColor = themeColor2
        
        nav1.tabBarItem = UITabBarItem(title: "发现", image: #imageLiteral(resourceName: "spot"), tag: 0)
        btnPH.tabBarItem = UITabBarItem(title: "打印", image: #imageLiteral(resourceName: "print_menu"), tag: 9)
        nav2.tabBarItem = UITabBarItem(title: "我的", image: #imageLiteral(resourceName: "wode"), tag: 1)
        
        
        tabController.setViewControllers([nav1, btnPH, nav2], animated: false)
        
        window?.rootViewController = tabController
        window?.makeKeyAndVisible()
        
        ChangyanSDK.registerApp("cysRubFVS", appKey: "08f4ce9a43b6473c08d0cf403c6d628f", redirectUrl: "", anonymousAccessToken: "lRTU3LghBcOtwGzEapYEsKt69Us55p8xBPbvxZ8EhW0")
        ChangyanSDK.setAllowSelfLogin(true)
        ChangyanSDK.setLoginViewController(FCLoginViewController())
        ChangyanSDK.setAllowAnonymous(false)
        ChangyanSDK.setAllowRate(false)
        ChangyanSDK.setAllowUpload(false)
        ChangyanSDK.setAllowQQLogin(false)
        ChangyanSDK.setAllowWeiboLogin(false)
        ChangyanSDK.setAllowSohuLogin(false)
        ChangyanSDK.setNavigationBackgroundColor(themeColor2)
        ChangyanSDK.setNavigationTintColor(UIColor.white)
        
        
        WXApi.registerApp("wxe7db23876dc7535a")
        
//        tencentApi = TencentApi()
        
        try? FileManager.default.createDirectory(atPath: imageCachesFloderPath, withIntermediateDirectories: true, attributes: nil)
        
        if launchOptions != nil {
            let url = launchOptions![UIApplicationLaunchOptionsKey.url] as? URL
            
            if url != nil{
                if url?.host == "safepay" {
                    AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
                        print("openurl:")
                        print(resultDic ?? "res nil")
                        if self.payView == nil{
                            self.payView = PayView(frame: self.tabController.view.frame)
                            self.tabController.view.addSubview(self.payView!)
                            
                            let oid = UserDefaults.standard.object(forKey: orderToDoID) as? String
                            let price = UserDefaults.standard.object(forKey: orderToDoPrice) as? String
                            
                            if oid != nil && price != nil{
                                self.payView?.openView(price, orderID: oid)
                                self.payView?.paymentResult(resultDic)
                            }
                            
                        }else{
                            self.payView?.paymentResult(resultDic)
                        }
                    })
                    return true
                }else{
                    let fileType = url?.absoluteString.components(separatedBy: ".").last
                    if fileType != nil{
                        if fileType == "doc" || fileType == "docx" || fileType == "ppt" || fileType == "pptx" || fileType == "xls" || fileType == "xlsx" || fileType == "pdf"{
                            tabController.openFile(url: url)
                            return true
                        }
                    }
                }
            }
            
            
            
        }
        
        return true
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        print("url: \(url)\nsourceApp:\n \(options)")
        if WXApi.handleOpen(url, delegate: self){
            return true
        }
        
        if QQApiInterface.handleOpen(url, delegate: tabController){
            return true
        }
        
        if TencentOAuth.handleOpen(url){
            return true
        }
        
        if url.host == "safepay" {
            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
                print("openurl:")
                print(resultDic ?? "res nil")
                self.payView?.paymentResult(resultDic)
            })
            return true
        }
        let fileType = url.absoluteString.components(separatedBy: ".").last
        if fileType != nil{
            if fileType == "doc" || fileType == "docx" || fileType == "ppt" || fileType == "pptx" || fileType == "xls" || fileType == "xlsx" || fileType == "pdf"{
                tabController.openFile(url: url)
                return true
            }
        }
        
        
        return false
    }
    
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        print(shortcutItem.localizedTitle)
        if shortcutItem.type == "scan" {
            tabController.presentedViewController?.dismiss(animated: true, completion: nil)
            self.tabController.fileView?.alpha = 0
            tabController.gotoScanCode()
        }
    }
    
    func onReq(_ req: BaseReq!) {
        
    }

    func onResp(_ resp: BaseResp!) {
        let re = resp as? SendAuthResp
        print(re.debugDescription)
        print(re?.description ?? "nil")
        if re != nil{
            
            let err = re!.errStr
            if err == nil {
                let code = re!.code
                print(code ?? "code nil")
                if code != nil{
                    
                    var tokenReq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=weChatAccessToken")!)
                    tokenReq.httpMethod = "POST"
                    tokenReq.httpBody = "code=\(code!)".data(using: .utf8)
                    URLSession.shared.dataTask(with: tokenReq, completionHandler: { (data, _, sessionErr) in
                        do{
                            if sessionErr != nil{
                                throw sessionErr!
                            }
                            print(String(data: data!, encoding: .utf8) ?? "data nil")
                            
                            let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                            let openid = jsonObj?.object(forKey: "openid") as? String
                            if openid != nil{
                                var loginReq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=WeChatLogin")!)
                                loginReq.httpMethod = "POST"
                                loginReq.httpBody = "openid=\(openid!)".data(using: .utf8)
                                
                                URLSession.shared.dataTask(with: loginReq, completionHandler: { (loginData, _, loginErr) in
                                    do{
                                        if loginErr != nil{
                                            throw loginErr!
                                        }
                                        
                                        print(String(data: loginData!, encoding: .utf8) ?? "data nil")
                                        
                                        let jsonObj = try JSONSerialization.jsonObject(with: loginData!, options: .allowFragments) as? NSDictionary
                                        let reCode = jsonObj?.object(forKey: "code") as? Int
                                        if reCode == 200{
                                            
                                            let cookies = HTTPCookieStorage.shared.cookies!
                                            let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                                            UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                                            UserDefaults.standard.set(code!, forKey: loginUserDefaultKeyName)
                                            
                                            DispatchQueue.main.async {
                                                self.tabController.presentedViewController?.dismiss(animated: true, completion: nil)
                                                self.tabController.fileView?.alpha = 0
                                                
                                                if self.wodeVCLoaded {
                                                    self.wodeVC.loadUserData()
                                                }
                                            }
                                            
                                            URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
                                                do{
                                                    if err != nil{
                                                        throw err!
                                                    }
                                                    
                                                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                                                    
                                                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                                                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                                                    
                                                    let nickName = jsonData?.object(forKey: "nickname") as? String
                                                    let face = jsonData?.object(forKey: "face") as? String
                                                    
                                                    if !ChangyanSDK.isLogin(){
                                                        ChangyanSDK.loginSSO(code!, userName: nickName ?? "", profileUrl: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo", imgUrl: face ?? "", complete: { (code, msg) in
                                                            if code == CYSuccess {
                                                                print("changyan login success:")
                                                                print(msg ?? "no respond")
                                                            }
                                                        })
                                                    }
                                                    
                                                }catch let ex{
                                                    print(ex)
                                                }
                                            }.resume()
                                            
                                            
                                        }else if reCode == 201 {
                                            DispatchQueue.main.async {
                                                self.tabController.selectedIndex = 2
                                                self.tabController.presentedViewController?.dismiss(animated: true, completion: nil)
                                                self.tabController.bgView.alpha = 0
                                                self.tabController.fileView?.alpha = 0
                                                self.wodeVC.gotoBindVC(type: .weixin, code: code, openid: openid)
                                            }
                                        }else{
                                            let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                            DispatchQueue.main.async {
                                                self.tabController.present(alert, animated: true, completion: nil)
                                            }
                                        }
                                        
                                        
                                        
                                    }catch let loginEx{
                                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                        DispatchQueue.main.async {
                                            self.tabController.present(alert, animated: true, completion: nil)
                                        }
                                        print(loginEx)
                                    }
                                }).resume()
                            }
                            
                            
                        }catch let ex{
                            print(ex)
                        }
                    }).resume()
                }
            }else{
                
            }
            
            
        }
    }
    
    
    
}

//http://114.215.105.95/print/?m=admin&c=login&a=userislogin

//http://114.215.105.95/print/?m=admin&c=user&a=userinfo

//let baseDomainName = "http://114.215.105.95"
let baseDomainName = "https://www.aimiaoyin.com"
let apiBaseDomainName = "\(baseDomainName)/print/index.php"

let sliderHeight:CGFloat = 200
//let categoryItemHeight:CGFloat = 80.0
let themeColor1 = UIColor(red: 127.0/255.0, green: 169.0/255.0, blue: 54.0/255.0, alpha: 1)
let themeColor2 = UIColor(red: 42.0/255.0, green: 42.0/255.0, blue: 42.0/255.0, alpha: 1)
let littleGrayColor = UIColor(red: 74.0/255.0, green: 74.0/255.0, blue: 74.0/255.0, alpha: 1)

let firstLaunchKey = "firstLaunch"

let loginUserDefaultKeyName = "userinfo"
let cookieKey = "cookie"

let userNickNameDefaultKeyName = "user_nickname"
let userSexDefaultKeyName = "user_sex"
let userAreaDefaultKeyName = "user_area"
let userSchoolDefaultKeyName = "user_school"
let orderListRefreshRequireKey = "orderListRefreshRequire"

let wodeImageKeyName = "wode_img"

let orderToDoID = "orderToDoID"
let orderToDoPrice = "orderToDoPrice"

func isLogin() ->Bool{
    return UserDefaults.standard.object(forKey: loginUserDefaultKeyName) != nil
}

func getUserInfo() -> Any?{
    return UserDefaults.standard.object(forKey: loginUserDefaultKeyName)
}

let CACHES_PATH = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let spotPageDataFileName = "spot_page_data.plist"
let imageCachesFloderPath = "\(CACHES_PATH)/image"

extension UIColor{
    static let extraLightGray = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 1)
}

let contributeText = "平凡或是一鸣惊人\n\n聆听或是大声呐喊\n\n活出你的样子\n\n发出你的声音\n\n请将你的稿件寄到\n\nimiaoyin@163.com\n\n这一次，不再沉默\n\n（请标明投稿的分类）"
let feedbackText = "请将你的反馈寄到\n\nimiaoyin@163.com"
let spotRefreshedTimeKey = "spotRefreshTime"
